package com.smart.expand.factory;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.FactoryBean;

import java.lang.reflect.Proxy;


/**
 * @author jiangjun
 */
public class ProxyBeanFactory{

    private static final Logger log = LoggerFactory.getLogger(ProxyBeanFactory.class);

    public <T> FactoryBean<T> getProxyFactoryBean(Class<T> clazz) {
        T instance = null;
        if (clazz.isInterface()){

        }else {
            try {
                instance = clazz.newInstance();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
        }
        T finalInstance = instance;
        Object factoryBean = Proxy.newProxyInstance(DefaultFactoryBean.class.getClassLoader(), DefaultFactoryBean.class.getInterfaces(), (proxy, method, args) -> {
            log.info("== ProxyBeanFactory::getProxyFactoryBean -> proxy:{}, method:{}, args:{} ==", proxy, method, args);
            if (method.getName().contains("getObject")) {
                return finalInstance;

            } else if (method.getName().contains("getObjectType")) {
                return clazz;
            }
            return proxy;
        });
        return FactoryBean.class.cast(factoryBean);
    }
}
